package com.lanou3g.ssoconsumer.web;

import com.lanou3g.ssoconsumer.bean.SSOResult;
import com.lanou3g.ssoconsumer.bean.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

@Controller
@RequestMapping("/user")
public class UserController {

    @Value("${sso.login.url}")
    private String loginUrl;

    @Autowired
    private RestTemplate restTemplate;

    // http://localhost:8899/get_user_by_token/
    @Value("${sso.get_user_by_token.url}")
    private String getUserByTokenUrl;

    @ResponseBody
    @RequestMapping("/get_by_token")
    public SSOResult getByToken(@CookieValue(name = "USER-TT", required = false) String token) {
        if(token == null) {
            System.out.println("会话超时，重新登录");
            SSOResult result = new SSOResult(500, "会话超时，重新登录");
            result.setData(loginUrl);
            return result;
        }

        // 拿token，请求sso服务，换取真正的用户信息
        ResponseEntity<UserInfo> entity = restTemplate.getForEntity(getUserByTokenUrl + token, UserInfo.class);
        if(entity.getStatusCode().value() == 200) {
            UserInfo userInfo = entity.getBody();
            if(userInfo != null) {
                System.out.println("当前登录用户：" + userInfo.getNickName());
                SSOResult result = new SSOResult(200, "");
                result.setData(userInfo.getNickName());
                return result;
            }
        }
        System.out.println("用token获取用户信息失败：无效token");
        SSOResult result = new SSOResult(500, "会话超时，重新登录");
        result.setData(loginUrl);
        return result;
    }

}
